//
//  JobsListViewController.swift
//  ezyform
//
//  Created by MoennigQ on 20/12/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import SwiftyJSON
import HandyJSON
import MJRefresh
import Alamofire
import RxSwift
import RxCocoa
import RxGesture
enum SkipToWhere: Int {//跳转到PVD Detail那个模块
    case Barcode = 1, Checklist = 2, Signature = 3, CESFile = 4, Panel = 5, Inverter = 6
}
class JobsListViewController: BaseViewController {
    fileprivate lazy var disposeBag = DisposeBag()
    var currentIndex: Int?
    //status drop down
    let jobStatusList = [PVDJobStatusName.all.rawValue,PVDJobStatusName.scheduled.rawValue,PVDJobStatusName.installing.rawValue,PVDJobStatusName.installed.rawValue,PVDJobStatusName.unqualified.rawValue]
    var selectedJobStatus: BehaviorRelay<String> = BehaviorRelay.init(value: PVDJobStatusName.all.rawValue)
    var selectedJobType: BehaviorRelay<String> = BehaviorRelay.init(value: JobType.all.rawValue)
    //暂存，再此打开选项框时，设置选中项
    var selectedJobStatusStr: String = PVDJobStatusName.all.rawValue
    var selectedJobTypeStr: String = JobType.all.rawValue
    //total pages for list
    var hearder: MJRefreshNormalHeader!
    var footer: MJRefreshBackNormalFooter!
    var currentPage: String = "1"
    var nextPage: String = ""
    let customView = PVDsListView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUIBinding()
        self.loadCombineData()
    }
    private func loadCombineData(loadingFlag: Bool = true, header: MJRefreshNormalHeader? = nil){
        self.loadMyInfomation()//是否有创建权限
        self.loadData(loadingFlag: loadingFlag,header: header)
    }
    private func initUIBinding(){
        self.view = customView
        self.customView.toDetailVCClosure = {[weak self](index, operType) in
            guard let strongSelf = self else {return}
            strongSelf.toDetailVC(index,operType: operType)
        }
        //上拉加载，下来刷新
        self.hearder =  MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerLoad(_:)))
        self.customView.tableView.mj_header = self.hearder
        //footer
        self.footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerLoad(_:)))
        self.customView.tableView.mj_footer = self.footer
        //点击头像
        self.customView.topCommonView.avatarImageView.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            InstallationDetailVCHelper.shared.toMeViewController(strongSelf)
        }).disposed(by: self.disposeBag)
        //点击search按钮
        self.customView.topCommonView.searchBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.searchBtnClick()
        }).disposed(by: disposeBag)
        //点击create job view中的按钮
        self.customView.createJobView.createJobBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.customView.topCommonView.createJobBtnClick()
        }).disposed(by: disposeBag)
        //订阅job status的变化，反应在label上
        selectedJobStatus.subscribe(onNext: { text in
            self.customView.searchStatusLabel.text = text
        }).disposed(by: self.disposeBag)
        //订阅job type的变化，反应在label上
        selectedJobType.subscribe(onNext: { text in
            self.customView.searchJobTypeLabel.text = text
        }).disposed(by: self.disposeBag)
        //点击job status显示
        self.customView.searchStatusLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.showStatusPopView()
        }).disposed(by: self.disposeBag)
        //点击Job type显示
        self.customView.searchJobTypeLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.showStatusPopView()
        }).disposed(by: self.disposeBag)
        //Retry
        self.customView.loadFaildView.retryBtn.rx.tap.subscribe {[weak self] _ in
            self?.loadCombineData()
        }.disposed(by: self.disposeBag)
    }
    //MARK: - 点击显示所有的状态
    @objc func showStatusPopView(){
        let view = PVDsListSearchPopView()
        view.initData(jobStatus: self.selectedJobStatusStr, jobType: self.selectedJobTypeStr)
        view.applyClosure = {[weak self] (jobStatus,jobType) in
            guard let strongSelf = self else { return  }
            strongSelf.selectedJobStatusStr = jobStatus
            strongSelf.selectedJobTypeStr = jobType
            //job status
            if jobStatus.contains(PVDJobStatusName.scheduled.rawValue + ",") && jobStatus.contains(PVDJobStatusName.installing.rawValue + ",") && jobStatus.contains(PVDJobStatusName.installed.rawValue + ",") && jobStatus.contains(PVDJobStatusName.unqualified.rawValue + ",") {//四个状态全选，则默认all
                strongSelf.selectedJobStatus.accept(PVDJobStatusName.all.rawValue)
            }else{
                var realStatus = jobStatus
                if jobStatus.contains(",") {
                    realStatus = String(jobStatus.prefix(jobStatus.count - 1))//去掉最后的逗号
                }
                strongSelf.selectedJobStatus.accept(realStatus)//去掉最后的逗号
            }
            //job type
            if jobType.contains(PVDsListJobType.swhJob.rawValue + ",") && jobType.contains(PVDsListJobType.pvdJob.rawValue + ",")  {//两个type全选，则默认all
                strongSelf.selectedJobType.accept(PVDsListJobType.all.rawValue)
            }else{
                var realJobType = jobType
                if jobType.contains(",") {
                    realJobType = String(jobType.prefix(jobType.count - 1))//去掉最后的逗号
                }
                strongSelf.selectedJobType.accept(realJobType)
            }
            
            strongSelf.loadData()
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - 加载数据
    func loadData(loadingFlag: Bool = true,header: MJRefreshNormalHeader? = nil, footer: MJRefreshBackNormalFooter? = nil,pageSize: Int? = nil){
        //set block
        let vm = JobsListService()
        vm.setBlockAfterNetwork({ (result, otherInfo) -> Void in
            header?.endRefreshing()
            footer?.endRefreshing()
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            //加载完再endrefreshing,解决上拉加载时tableview抖动死循环请求网络无限次加载的问题
            //header data
            if let pageInfo = otherInfo{
                self.nextPage = ((pageInfo.object(forKey: "X-Next-Page") as? String) ?? "")
            }else{
                self.nextPage = ""
            }
            if self.nextPage != "" {
                self.footer.resetNoMoreData()
            }else{
                self.footer.endRefreshingWithNoMoreData()
            }
            
            VersionManager.shared.checkForceUpdateVersion() 
            //data list
            guard let res = result else {return}
            let json = JSON(res)
            if let data = JSONDeserializer<InstallationListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<InstallationListModel>{
                
                if self.currentPage == "1" {
                    self.customView.dataObserver.accept(data)
                }else{
                    let temp = data
                    self.customView.dataObserver.accept(self.customView.dataObserver.value + temp)
                }
                
                self.customView.showResultView(loadSuccessFlag: true,haveDataFlag: (self.customView.dataObserver.value.count > 0 ? true: false),searchStatus: self.selectedJobStatus.value )
            }
        }) { (code, error) -> Void in
            //加载完再endrefreshing,解决上拉加载时tableview抖动死循环请求网络无限次加载的问题
            if let tempHeader = header {
                tempHeader.endRefreshing()
            }
            if let tempFooter = footer {
                tempFooter.endRefreshing()
            }
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            //显示加载失败的试图
            if self.customView.dataObserver.value.count == 0{
                self.customView.showResultView(loadSuccessFlag: false, haveDataFlag: false)
                Tool().showErrorInfo(code, error)
            }
        }
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView(NSLocalizedString("Loading", comment: ""))
        }
        if let tempHeader = header {
            tempHeader.beginRefreshing()
        }
        if let tempFooter = footer {
            tempFooter.beginRefreshing()
        }
        var combineStr = "?page=\(self.currentPage)" + self.getQueryStr()
        if let page = pageSize {
            combineStr += "&per_page=\(page)"//从detail返回刷新list用
        }
        vm.getInstallationsListForV2(combineStr)
    }
    //MARK: - 加载个人信息，是否显示create job 权限
    private func loadMyInfomation(){
        SystemInfoService.shared().loadMyInformation()
    }
    func searchBtnClick(){
        let vc = JobsInstallationsSearchViewController()
//        vc.searchModule = .installations
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc func headerLoad(_ header: MJRefreshNormalHeader){
        self.currentPage = "1"
        self.loadCombineData(loadingFlag: false,header: header)
    }
    
    @objc func footerLoad(_ footer: MJRefreshBackNormalFooter){
        self.currentPage = self.nextPage
        self.loadData(loadingFlag: false,footer: footer)
    }
    func getQueryStr()-> String{
        var queryStr = ""
        if self.selectedJobStatus.value != PVDJobStatusName.all.rawValue{
            queryStr += "&status=" + self.selectedJobStatus.value
        }
        if self.selectedJobType.value == PVDsListJobType.pvdJob.rawValue {
            queryStr += "&job_type=1"
        }else if self.selectedJobType.value == PVDsListJobType.swhJob.rawValue {
            queryStr += "&job_type=2"
        }
        return queryStr
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        //set background color of navigation bar
        self.tabBarController?.tabBar.isHidden = false
        //启动APP
        Tool().handleRemoteNotificationForLaunchAPP()
    }
    
}
extension JobsListViewController: UIScrollViewDelegate{
    func toDetailVC(_ index: Int, operType: PVDsListCellOperType? = nil){
        self.currentIndex = index
        let model = self.customView.dataObserver.value[index]
        //
        JobDetailModelHelper.shared.jobDetailModel = PVDDetailModel()
        JobDetailModelHelper.shared.jobDetailModel.pvd_id = model.pvd_id
        //记录Crash log时的pvd id和gwt id
        SentryHelper().setCrashLogCustomInfo(pvdId: model.pvd_id ,gwtNo: model.gwt_id)
        JobDetailModelHelper.shared.jobDetailModel.gwt_id = model.gwt_id
        JobDetailModelHelper.shared.jobDetailModel.owner_address.type_name = model.full_name
        if model.solar_water_heater {//swh
            let vc = SWHDetailViewController()
            vc.reloadPVDsListClosure = {[weak self] in
                guard let strongSelf = self else { return  }
                strongSelf.loadData(loadingFlag: false, pageSize: strongSelf.customView.dataObserver.value.count)
                
            }
            switch operType {
            case .barcode:
                vc.skipToWhere = .Barcode
            case .checklist:
                vc.skipToWhere = .Checklist
            case .signature:
                vc.skipToWhere = .Signature
            default:
                break
            }
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: false)
        }else{//solar
            let vc = JobDetailViewController()
            vc.reloadPVDsListClosure = {[weak self] in
                guard let strongSelf = self else { return  }
                strongSelf.loadData(loadingFlag: false, pageSize: strongSelf.customView.dataObserver.value.count)
            }
            //
            switch operType {
            case .barcode:
                vc.skipToWhere = self.skipToWhereFoBarcode(model)
            case .checklist:
                vc.skipToWhere = .Checklist
            case .signature:
                vc.skipToWhere = .Signature
            case .cesfile:
                vc.skipToWhere = .CESFile
            default:
                break
            }
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    //
    private func skipToWhereFoBarcode(_ model: InstallationListModel)->SkipToWhere{
        var toWhere: SkipToWhere = .Panel
        let panelCnt = (model.new_panel_number_count)
        let panelFinishCnt = (model.new_panel_number_finished_count)
        let inverterCnt = (model.inverter_number_count)
        let inverterFinishCnt = (model.inverter_number_finished_count)
        if model.is_new_stc_form && panelCnt <= panelFinishCnt && inverterCnt > inverterFinishCnt{//安装日期在2022-04-01以后的Job才这样处理，panel数量已经扫够，inverter数量不够，就跳转到Inverter，其他情况跳转到Panel
            toWhere = .Inverter
        }
        return toWhere
    }
}
